<template>
  <div>
    <content-panel
      ref="contentRef"
      title="角色管理"
      :ops="{add:'permission:role:add', update: 'permission:role:edit', delete: 'permission:role:delete',export:'permission:role:export'}"
      :search-props="searchProps"
      search-label-width="55px"
      :table-props="tableProps"
      delete-api="deleteRole"
      get-api="getRole"
      list-api="getRoles"
      :import-and-export="{exportUrl:'/permission/role/export'}"
      @handle-add="handleAdd"
      @handle-update="handleUpdate"
    >
      <template #status="scope">
        <el-switch
          v-model="scope.row.status"
          active-value="0"
          inactive-value="1"
          @click="handleStatusChange(scope.row)"
        />
      </template>
      <template #operate="scope">
        <div class="operation-buttons">
          <el-button
            v-if="scope.row.id !== 1"
            v-has-perm="['permission:role:edit']"
            size="small"
            link
            :icon="Edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            v-has-perm="['permission:role:delete']"
            size="small"
            link
            :icon="Delete"
            style="color: #F56C6C"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
          <el-dropdown
            v-has-perm="['permission:role:edit']"
            size="small"
            @command="(command) => handleCommand(command, scope.row)"
          >
            <el-button
              size="small"
              link
              :icon="DArrowRight"
              style="color: #23cf69"
            >更多
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  command="handleDataScope"
                  :icon="CircleCheck"
                >数据权限
                </el-dropdown-item>
                <el-dropdown-item
                  command="handleAuthUser"
                  :icon="User"
                >分配用户
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </template>
    </content-panel>


    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" style="top: 6vh;" width="40vw" append-to-body>
      <el-scrollbar max-height="70vh">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="6rem">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="form.roleName" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item prop="roleKey">
            <template #label>
              <span>
                <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
                  <el-icon><question-filled /></el-icon>
                </el-tooltip>
                权限字符
              </span>
            </template>
            <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
          </el-form-item>
          <el-form-item label="角色顺序" prop="sort">
            <el-input-number v-model="form.sort" controls-position="right" :min="0" />
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in $dict.normal_disable"
                :key="dict.value"
                :value="dict.value"
              >{{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="菜单权限">
            <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
            <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选
            </el-checkbox>
            <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动
            </el-checkbox>
            <el-tree
              ref="menuRef"
              class="tree-border"
              :data="menuOptions"
              show-checkbox
              node-key="id"
              :check-strictly="!form.menuCheckStrictly"
              empty-text="加载中，请稍候"
              :props="defaultProps"
            />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" type="textarea" :autosize="{minRows: 4, maxRows: 8}" placeholder="请输入内容" />
          </el-form-item>
        </el-form>
      </el-scrollbar>


      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 分配角色数据权限对话框 -->
    <el-dialog :title="title" v-model="openDataScope" style="top: 6vh;" width="40vw" append-to-body>
      <el-scrollbar max-height="70vh">
        <el-form :model="form" label-width="6rem">
          <el-form-item label="角色名称">
            <el-input v-model="form.roleName" :disabled="true" />
          </el-form-item>
          <el-form-item label="权限字符">
            <el-input v-model="form.roleKey" :disabled="true" />
          </el-form-item>
          <el-form-item label="权限范围">
            <el-select v-model="form.dataScope" @change="dataScopeSelectChange">
              <el-option
                v-for="item in dataScopeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-show="form.dataScope === '2'" label="数据权限">
            <el-checkbox v-model="scopeExpand" @change="handleCheckedTreeExpand($event, 'scope')">展开/折叠</el-checkbox>
            <el-checkbox v-model="scopeNodeAll" @change="handleCheckedTreeNodeAll($event, 'scope')">全选/全不选
            </el-checkbox>
            <el-checkbox v-model="form.scopeCheckStrictly" @change="handleCheckedTreeConnect($event, 'scope')">父子联动
            </el-checkbox>
            <el-tree
              ref="scopeRef"
              class="tree-border"
              :data="scopeOptions"
              show-checkbox
              default-expand-all
              node-key="id"
              :check-strictly="!form.scopeCheckStrictly"
              empty-text="加载中，请稍候"
              :props="defaultProps"
            />
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDataScope">确 定</el-button>
          <el-button @click="cancelDataScope">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { CircleCheck, DArrowRight, Delete, Edit, QuestionFilled, User } from '@element-plus/icons-vue'

const router = useRouter()
const contentRef = ref(null)
const form = ref({})
const title = ref('')
const open = ref(false)
const openDataScope = ref(false)
const menuExpand = ref(false)
const menuNodeAll = ref(false)
const menuRef = ref(null)
const menuOptions = ref([])
const defaultProps = {
  children: 'children',
  label: 'label'
}
const proxy = getCurrentInstance()
const scopeExpand = ref(true)
const scopeNodeAll = ref(false)
const scopeOptions = ref([])
const scopeRef = ref(null)
/** 数据范围选项*/
const dataScopeOptions = ref([
  {value: "1", label: "全部数据权限"},
  {value: "2", label: "自定数据权限"},
  {value: "3", label: "本部门数据权限"},
  {value: "4", label: "本部门及以下数据权限"},
  {value: "5", label: "仅本人数据权限"}
])
/** 搜索框配置 */
const searchProps = ref([
  {label: '角色名称', prop: 'roleName', type: 'input', labelWidth: 5},
  {label: '权限字符', prop: 'roleKey', type: 'input', labelWidth: 5},
  {label: '状态', prop: 'status', type: 'select', options: $dict.normal_disable, labelWidth: 5},
  {label: '创建时间', prop: 'createTime', type: 'date', labelWidth: 5}
])

/** 表格配置 */
const tableProps = [
  {label: '角色编号', prop: 'id'},
  {label: '角色名称', prop: 'roleName'},
  {label: '权限字符', prop: 'roleKey'},
  {label: '显示顺序', prop: 'sort'},
  {label: '状态', prop: 'status', type: 'status'},
  {label: '创建时间', prop: 'createTime'},
  {label: '显示顺序', prop: 'sort'},
  {label: '操作', type: 'operate', width: 200}
]

const rules = {
  roleName: [
    {required: true, message: '角色名称不能为空', trigger: 'blur'}
  ],
  roleKey: [
    {required: true, message: '权限字符不能为空', trigger: 'blur'}
  ],
  sort: [
    {required: true, message: '角色顺序不能为空', trigger: 'blur'}
  ]
}

function handleStatusChange(row) {
  const text = row.status === '0' ? '启用' : '停用'
  $xl.modal.confirm('确认要"' + text + '""' + row.roleName + '"角色吗？').then(() => {
    $xl.apis.changeRoleStatus({
      params: {
        id: row.id,
        status: row.status
      }
    }).then(() => {
      $xl.modal.msgSuccess(text + '成功')
    }).catch(function () {
      row.status = row.status === '0' ? '1' : '0'
    })
  }).catch(() => {
  })
}

function handleCommand(command, row) {
  switch (command) {
    case 'handleDataScope':
      handleDataScope(row)
      break
    case 'handleAuthUser':
      handleAuthUser(row)
      break
    default:
      break
  }
}

// 树权限（展开/折叠）
function handleCheckedTreeExpand(value, type) {
  if (type === "menu") {
    const treeList = menuOptions.value
    for (let i = 0 ; i < treeList.length ; i++) {
      menuRef.value.store.nodesMap[treeList[i].id].expanded = value
    }
  } else if (type === "scope") {
    const treeList = scopeOptions.value
    for (let i = 0 ; i < treeList.length ; i++) {
      scopeRef.value.store.nodesMap[treeList[i].id].expanded = value
    }
  }
}

// 树权限（全选/全不选）
function handleCheckedTreeNodeAll(value, type) {
  if (type === "menu") {
    menuRef.value.setCheckedNodes(value ? menuOptions.value : [])
  } else if (type === "scope") {
    scopeRef.value.setCheckedNodes(value ? scopeOptions.value : [])
  }
}

// 树权限（父子联动）
function handleCheckedTreeConnect(value, type) {
  if (type === 'menu') {
    form.value.menuCheckStrictly = !!value
  } else if (type === 'scope') {
    form.value.scopeCheckStrictly = !!value
  }
}

/** 查询菜单树结构 */
function getMenuTreeSelect() {
  $xl.apis.treeSelect().then(response => {
    menuOptions.value = response.data
  })
}

// 所有菜单节点数据
function getMenuAllCheckedKeys() {
  // 目前被选中的菜单节点
  const checkedKeys = menuRef.value.getCheckedKeys()
  // 半选中的菜单节点
  const halfCheckedKeys = menuRef.value.getHalfCheckedKeys()
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
  return checkedKeys
}

function submitForm() {
  proxy.refs.formRef.validate(valid => {
    if (valid) {
      if (form.value.id !== undefined) {
        form.value.menuIds = getMenuAllCheckedKeys()
        $xl.apis.updateRole({params: form.value}).then(() => {
          $xl.modal.msgSuccess('修改成功')
          open.value = false
          contentRef.value.getList()
        })
      } else {
        form.value.menuIds = getMenuAllCheckedKeys()
        $xl.apis.saveRole({params: form.value}).then(() => {
          $xl.modal.msgSuccess('新增成功')
          open.value = false
          contentRef.value.getList()
        })
      }
    }
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: undefined,
    roleName: undefined,
    roleKey: undefined,
    sort: 0,
    scopeId: undefined,
    status: '0',
    menuIds: [],
    scopeIds: [],
    menuCheckStrictly: true,
    scopeCheckStrictly: true,
    remark: undefined
  }
  menuExpand.value = false
  menuNodeAll.value = false
  scopeExpand.value = true
  scopeNodeAll.value = false

  // 将 menuRef 的检查和重置移到 nextTick 中
  nextTick(() => {
    if (menuRef.value) {
      menuRef.value.setCheckedKeys([])
    }
    if (proxy.refs.formRef) {
      proxy.refs.formRef.resetFields()
    }
  })
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  getMenuTreeSelect()
  open.value = true
  title.value = '添加角色'
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const roleId = row.id || contentRef.value.getSelectedIds()
  $xl.apis.getRole({
    jointUrl: '/' + roleId
  }).then(response => {
    form.value = response.data
    open.value = true
    nextTick(() => {
      /** 根据角色ID查询菜单树结构 */
      $xl.apis.roleMenuTreeSelect({
        jointUrl: '/' + roleId
      }).then(res => {
        menuOptions.value = res.menus
        const checkedKeys = res.checkedKeys
        checkedKeys.forEach((v) => {
          nextTick(() => {
            menuRef.value.setChecked(v, true, false)
          })
        })
      })
    })
    title.value = '修改角色'
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const roleIds = row.id || contentRef.value.getSelectedIds()
  $xl.modal.confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？').then(() => {
    $xl.apis.deleteRole({
      jointUrl: '/' + roleIds
    }).then(() => {
      contentRef.value.getList()
      $xl.modal.msgSuccess('删除成功')
    })
  }).catch(() => {
  })
}


/** 分配数据权限操作 */
function handleDataScope(row) {
  reset()
  const roleScopeTreeSelect = getRoleScopeTreeSelect(row.id)
  // 获取角色权限
  $xl.apis.getRole({
    jointUrl: '/' + row.id
  }).then(response => {
    form.value = response.data
    openDataScope.value = true
    nextTick(() => {
      roleScopeTreeSelect.then(res => {
        nextTick(() => {
          if (scopeRef.value) {
            scopeRef.value.setCheckedKeys(res.checkedKeys)
          }
        })
      })
    })
    title.value = '分配数据权限'
  })
}

/** 根据角色ID查询部门树结构 */
function getRoleScopeTreeSelect(id) {
  return $xl.apis.roleScopeTreeSelect({
    jointUrl: '/' + id
  }).then(response => {
    // 首先获取数据范围树结构列表
    scopeOptions.value = response.scopes
    return response
  })
}

/** 分配用户操作 */
function handleAuthUser(row) {
  router.push('/common/permission/role-auth/user/' + row.id)
}

/** 选择角色权限范围触发 */
function dataScopeSelectChange(value) {
  if (value !== '2') {
    scopeRef.value.setCheckedKeys([])
  }
}

/** 提交按钮（数据权限） */
function submitDataScope() {
  if (form.value.id !== undefined) {
    form.value.scopeIds = getScopeAllCheckedKeys()
    $xl.apis.updateDataScope({params: form.value}).then(response => {
      $xl.modal.msgSuccess('修改成功')
      openDataScope.value = false
      contentRef.value.getList()
    })
  }
}

/** 取消按钮（数据权限）*/
function cancelDataScope() {
  openDataScope.value = false
  reset()
}

/** 所有部门节点数据 */
function getScopeAllCheckedKeys() {
  // 目前被选中的部门节点
  const checkedKeys = scopeRef.value.getCheckedKeys()
  // 半选中的部门节点
  const halfCheckedKeys = scopeRef.value.getHalfCheckedKeys()
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
  return checkedKeys
}


</script>


<style scoped>
.operation-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}
</style>
